<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选项A" prop="optionA">
        <el-input
          v-model="queryParams.optionA"
          placeholder="请输入选项A"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选项B" prop="optionB">
        <el-input
          v-model="queryParams.optionB"
          placeholder="请输入选项B"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维度" prop="dimension">
        <el-input
          v-model="queryParams.dimension"
          placeholder="请输入维度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选A的分数" prop="scoreIfA">
        <el-input
          v-model="queryParams.scoreIfA"
          placeholder="请输入选A的分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选B的分数" prop="scoreIfB">
        <el-input
          v-model="queryParams.scoreIfB"
          placeholder="请输入选B的分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['MhQuestions:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['MhQuestions:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['MhQuestions:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['MhQuestions:question:export']"
        >导出</el-button>
      </el-col>
      <!-- 添加同步按钮 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
        >同步</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="问题文本" align="center" prop="text" />
      <el-table-column label="选项A" align="center" prop="optionA" />
      <el-table-column label="选项B" align="center" prop="optionB" />
      <el-table-column label="维度" align="center" prop="dimension" />
      <el-table-column label="选A的分数" align="center" prop="scoreIfA" />
      <el-table-column label="选B的分数" align="center" prop="scoreIfB" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['MhQuestions:question:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['MhQuestions:question:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改测试问题库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问题文本" prop="text">
          <el-input v-model="form.text" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="选项A" prop="optionA">
          <el-input v-model="form.optionA" placeholder="请输入选项A" />
        </el-form-item>
        <el-form-item label="选项B" prop="optionB">
          <el-input v-model="form.optionB" placeholder="请输入选项B" />
        </el-form-item>
        <el-form-item label="维度" prop="dimension">
          <el-input v-model="form.dimension" placeholder="请输入维度" />
        </el-form-item>
        <el-form-item label="选A的分数" prop="scoreIfA">
          <el-input v-model="form.scoreIfA" placeholder="请输入选A的分数" />
        </el-form-item>
        <el-form-item label="选B的分数" prop="scoreIfB">
          <el-input v-model="form.scoreIfB" placeholder="请输入选B的分数" />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 同步对话框 -->
    <el-dialog title="同步题目" :visible.sync="syncOpen" width="1200px" append-to-body :close-on-click-modal="false">
      <el-form :model="syncForm" label-width="100px">
        <el-row :gutter="20" align="middle">
          <el-col :span="8">
            <el-form-item label="题目数量"> 
              <el-input-number v-model="syncForm.count" :min="1" :max="1000" label="请输入要生成的题目数量"></el-input-number>  
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="版本号"> 
              <el-input-number v-model="syncForm.version" :min="1" :max="1000" label="请输入版本号"></el-input-number>  
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item> 
              <el-button type="primary" @click="handleGenerate">生成</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="cancelSync">取消</el-button>
      </div>
      
      <!-- 题目预览表格 -->
      <el-table :data="syncQuestionList" height="400" style="margin-top: 20px;">
        <el-table-column label="ID" prop="id" width="60"></el-table-column>
        <el-table-column label="问题文本" prop="text"></el-table-column>
        <el-table-column label="选项A" prop="optionA" width="100"></el-table-column>
        <el-table-column label="选项B" prop="optionB" width="100"></el-table-column>
        <el-table-column label="维度" prop="dimension" width="100"></el-table-column>
        <el-table-column label="选A的分数" prop="scoreIfA" width="100"></el-table-column>
        <el-table-column label="选B的分数" prop="scoreIfB" width="100"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/MhQuestions/question"
import { GetAiCreate, syncAiCreate } from "@/api/MhQuestions/question"

export default {
  name: "Question",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试问题库表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        text: null,
        optionA: null,
        optionB: null,
        dimension: null,
        scoreIfA: null,
        scoreIfB: null,
        status: null,
        version: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        text: [
          { required: true, message: "问题文本不能为空", trigger: "blur" }
        ],
        optionA: [
          { required: true, message: "选项A不能为空", trigger: "blur" }
        ],
        optionB: [
          { required: true, message: "选项B不能为空", trigger: "blur" }
        ],
        dimension: [
          { required: true, message: "维度不能为空", trigger: "blur" }
        ],
        scoreIfA: [
          { required: true, message: "选A的分数不能为空", trigger: "blur" }
        ],
        scoreIfB: [
          { required: true, message: "选B的分数不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      },
      // 同步对话框是否显示
      syncOpen: false,
      // 同步表单参数
      syncForm: {
        count: 20,
        version: 1
      },
      // 同步题目数据
      syncQuestionList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询测试问题库列表 */
    getList() {
      this.loading = true
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        text: null,
        optionA: null,
        optionB: null,
        dimension: null,
        scoreIfA: null,
        scoreIfB: null,
        createTime: null,
        updateTime: null,
        status: null,
        version: null,
        sort: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加测试问题库"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改测试问题库"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除测试问题库编号为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 同步按钮操作 */
    handleSync() {
      this.syncOpen = true
      this.syncQuestionList = []
    },
    /** 取消同步 */
    cancelSync() {
      this.syncOpen = false
      this.syncForm.count = 10
    },
    /** 生成题目 */
    handleGenerate() {
      // 显示加载提示
      const loading = this.$loading({
        lock: true,
        text: '正在加载题目，请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 加载本地JSON文件
      fetch('/mbti_200.json')
        .then(response => response.json())
        .then(data => {
          // 关闭加载提示
          loading.close();
          
          // 根据用户指定的数量截取题目
          const questions = data.questions.slice(0, this.syncForm.count);
          
          // 处理返回的数据
          this.syncQuestionList = questions.map(item => {
            return {
              id: item.id,
              text: item.text,
              optionA: item.option_a,
              optionB: item.option_b,
              dimension: item.dimension,
              scoreIfA: item.score_if_a,
              scoreIfB: item.score_if_b
            }
          })
          this.$modal.msgSuccess(`成功加载${questions.length}道题目`)
        })
        .catch(error => {
          // 关闭加载提示
          loading.close();
          
          console.error("加载题目失败:", error)
          this.$modal.msgError("加载题目失败")
        })
    },
    /** 保存题目 */
    handleSave() {
      if (!this.syncForm.version) {
        this.$modal.msgError("请先输入版本号")
        return
      }
      
      if (!this.syncQuestionList || this.syncQuestionList.length === 0) {
        this.$modal.msgError("请先生成题目")
        return
      }
      
      // 构造请求参数
      const requestData = {
        version: this.syncForm.version,
        questions: this.syncQuestionList.map(item => {
          return {
            id: item.id,
            text: item.text,
            option_a: item.optionA,
            option_b: item.optionB,
            dimension: item.dimension,
            score_if_a: item.scoreIfA,
            score_if_b: item.scoreIfB
          }
        })
      }
      
      // 调用保存接口
      syncAiCreate(requestData).then(response => {
        this.$modal.msgSuccess("保存成功")
        this.syncOpen = false
      }).catch(error => {
        console.error("保存失败:", error)
        this.$modal.msgError("保存失败")
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('MhQuestions/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
  .el-dialog__body {
    padding: 10px 20px;
  }
</style>
